type Config = {
	hash: string;
	width?: number;
	height?: number;
};

//打开新的父子窗口
export const openChildWindow = (config: Config) => {
	window.$.send('GENERAL-SUB-WINDOW-OPEN', { config });
};

//发送父子窗口消息
export const sendTabMessage = (channel: string, message?: any) => {
	const s = { channel, message, _ts: new Date().getTime() };
	window.localStorage.setItem('sendTabMessage', JSON.stringify(s));
};

//持续监听父子消息
export const onTabMessage = (channel: string, call: any) => {
	const handler = (e: any) => {
		if (e.key == 'sendTabMessage') {
			const { channel: listenChannel, message } = JSON.parse(e.newValue ?? '');
			if (listenChannel == channel) {
				call(message);
			}
		}
	};
	window.removeEventListener('storage', handler);
	window.addEventListener('storage', handler);
};

//接收父子窗口一次性消息
export const onTabOnceMessage = (channel: string) => {
	return new Promise((resolve) => {
		const func = (e: any) => {
			if (e.key == 'sendTabMessage') {
				const { channel: listenChannel, message } = JSON.parse(e.newValue ?? '');
				if (listenChannel == channel) {
					window.removeEventListener('storage', func);
					resolve(message);
				}
			}
		};
		window.addEventListener('storage', func);
	});
};
